import { cityList } from "../config/cityList";
import { calcPrice, getCityInfo } from "../thirdServices/api";
import { gcjGps } from "../utils/gps";

const getPrice = async (city_id, order_time, vehicleInfo, addr_list) => {
  const params = {
    addr_list,
    order_time,
    ...vehicleInfo,
    city_id,
    city_info_revision: 809,
    client_edition: 'NORMAL_VERSION',
    custom_service_list: 3,
    type: 0,
    risk_params: {
        brand: 'iPhone',
        model: 'iPhone 14 Pro<iPhone15,2>',
        osversion: '17.3.1',
        os: 'ios',
        app_key: '',
        appversion: 4469,
        bssid: 'f4:6d:2f:3a:5c:e3',
        device_sign: '',
        imei: '',
        lat: '',
        lng: '',
        mac: '',
        nettype: 'WIFI',
        ostype: 2,
        out_user_id: '',
        push_cid: '',
        ssid: 'mmmm',
        uuid: '',
    }
  };
  const res = await calcPrice(params);
  if (res.data.ret === 0) {
      const data = res.data.data;
      const price = data.priceConditions[0];
      const calcRes = {
          route_id: 1,
          vehicle_type: data.vehicleInfo.orderVehicleName, // 车型
          is_multiple_price: price.priceItem.filter(item => ![1, 2].includes(item.priceType)).length > 0, // 多因素
          total_distance: price.distanceInfo.distanceTotal, // 总里程
          start_distance: 5 * 1000, // 起步里程
          start_price: price.priceItem.find(item => item.priceType === 1)?.preValueFen, // 起步价格
          exceed_distance: (price.distanceInfo.distanceTotal - 5 * 1000), // 超起步的里程
          exceed_price: price.priceItem.find(item => item.priceType === 2)?.preValueFen || 0, // 超起步的价格
          distance_price: price.priceInfo.originalPrice, // 应付价格
          surcharge_service_type: price.priceItem.filter(item => ![1, 2].includes(item.priceType)).map(item => item.priceType).join(','), // 附加类型
          surcharge_service_price: price.priceItem.filter(item => ![1, 2].includes(item.priceType)).map(item => item.preValueFen).join(','),// 附加金额
          coupon_type: price.couponInfo.couponItem.length ? price.couponInfo.couponItem : 0, //  优惠
          coupon: price.couponInfo.couponItem.length ? price.couponInfo.couponItem : 0,// 优惠金额
          finalPriceWithoutCoupon: price.priceInfo.forCouponPrice,
          finalPrice: price.priceInfo.finalPrice,
          orderTime: price.distanceInfo.duration
      };
      return calcRes;
  } else {
      throw new Error(res.data.msg);
  }
};

const getVehicleInfo = async (cityId, targetVehicle: string) => {
  const params = {
    city_id: cityId,
    lat_lon: {
        lat: 0,
        long: 0
    }
};
  const res = await getCityInfo(params);
  if (res.data.ret === 0) {
      const list = res.data.data.vehicle_item;
      const vehicle = list.find((item) => item.name === targetVehicle);
      if (vehicle) {
          const standard_order_vehicle_id = vehicle.standard_order_vehicle_id;
          const order_vehicle_id = vehicle.order_vehicle_id;
          const std_tag = vehicle.vehicle_std_item.filter(item => item.is_checked === 1).map(item =>item.name);
          return {
            standard_order_vehicle_id,
            order_vehicle_id,
            std_tag
          };
      } else {
        throw new Error('没有找到对应车辆：' + targetVehicle);
      }
  } else {
    throw new Error(res.data.msg);
  }
}

const getTime = (orderTime: string) => {
  const time = orderTime.split(':');
  const date = new Date();
  date.setHours(Number(time[0]));
  date.setMinutes(Number(time[1]));
  date.setSeconds(Number(time[2]));

  return Math.floor(date.getTime() / 1000);
}

export const calc = async (cityName, district, vehicleName, fromAddrStr, toAddrStr, orderTime, fromLon, fromLat, toLon, toLat) => {
  const city = cityList.find(item => item.name === cityName);

  if (city) {
    const vehicleInfo = await getVehicleInfo(city.city_id, vehicleName);

    const fromAddr = {
      addr: fromAddrStr,
      city_id: city.city_id,
      district_name: district,
      lat_lon: {lon: fromLon, lat: fromLat},
      lat_lon_gcj: gcjGps(fromLat, fromLon, false),
      name: fromAddrStr
    };

    const toAddr = {
      addr: toAddrStr,
      city_id: city.city_id,
      district_name: district,
      lat_lon: {lon: toLon, lat: toLat},
      lat_lon_gcj: gcjGps(toLat, toLon, false),
      name: toAddrStr
    };

    const priceInfo = await getPrice(city.city_id, getTime(orderTime), vehicleInfo, [fromAddr, toAddr]);
    return {
      ...priceInfo,
      cityId: city.city_id
     };
  } else {
    throw new Error('未找到城市信息');
  }
};